import time,datetime,requests,json,psutil,os,pyautogui,cv2,pyscreeze,sys,schedule,time
# import win32gui
import win32con
from win32 import win32gui
# from win32 import win32con



import configparser,os,sys

pyPath=os.path.dirname(os.path.realpath(sys.argv[0]))
pyautogui.FAILSAFE=False
config = configparser.ConfigParser()
print(os.path.join(os.getcwd(), 'readConfig.ini'))
config.read(os.path.join(os.getcwd(), 'readConfig.ini'), encoding="utf-8")  # 读取config.ini
每天阅读时间 = config.getint("Params", "dayReadTime")   # 1小时
测试标识 = config.getint("Params", "isTest")
开始阅读时间 = config.getint("Params", "beginTime")
程序休眠时间 = config.getint("Params", "sleepTime")

def send_wechat_msg(content):
    webhook_url= "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=b20915c0-1822-485c-8a69-ee0a9f594014"
    data = {"msgtype": "text",
    "mentioned_list":["张文强"],
    "text": {"content": content}}
    proxies = {
        "http": None,
        "https": None,
    }
    header = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.40 Safari/537.36 Edg/87.0.664.24'
    }
    requests.packages.urllib3.disable_warnings()
    r = requests.post(url=webhook_url,headers=header, data=json.dumps(data, ensure_ascii=False).encode('utf-8'), verify=False,proxies=proxies)
    return r.text, r.status_code

def getButton(targetImage):
    # 屏幕缩放系数 mac缩放是2 windows一般是1
    screenScale = 1
    # 事先读取按钮截图
    target = cv2.imread(targetImage, cv2.IMREAD_GRAYSCALE)
    # 先截图
    screenshot = pyscreeze.screenshot('my_screenshot.png')
    # 读取图片 灰色会快
    temp = cv2.imread(r'my_screenshot.png', cv2.IMREAD_GRAYSCALE)
    theight, twidth = target.shape[:2]
    tempheight, tempwidth = temp.shape[:2]
    # 先缩放屏幕截图 INTER_LINEAR INTER_AREA
    scaleTemp = cv2.resize(temp, (int(tempwidth / screenScale), int(tempheight / screenScale)))
    stempheight, stempwidth = scaleTemp.shape[:2]
    # 匹配图片
    res = cv2.matchTemplate(scaleTemp, target, cv2.TM_CCOEFF_NORMED)
    mn_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
    if (max_val >= 0.9):
        # 计算出中心点
        top_left = max_loc
        bottom_right = (top_left[0] + twidth, top_left[1] + theight)
        tagHalfW = int(twidth / 2)
        tagHalfH = int(theight / 2)
        tagCenterX = top_left[0] + tagHalfW
        tagCenterY = top_left[1] + tagHalfH
        # 左键点击屏幕上的这个位置
        pyautogui.click(tagCenterX, tagCenterY, button='left')
    else:
        print("没找到")


def 定时关闭和启动策略文件(文件地址,断开时间列表=["15:30","02:35"],启动时间列表=["08:50","20:50"]):
    while True:
        pids = set(psutil.pids())
        os.system("start  cmd   /K python "+文件地址)
        time.sleep(0.1)
        pids2 = set(psutil.pids())
        任务进程=pids2-pids

        while True:
            if time_to_str(time.time())[11:16] in 断开时间列表:
                for x in 任务进程:
                    os.system("taskkill /pid  " +str(x))
                    print(f"{time_to_str(time.time())},关闭服务")
                任务进程=[]
                break
            time.sleep(60)  # 每1分钟检测一次
        while True:
            if time_to_str(time.time())[11:16] in 启动时间列表:
                if time.localtime().tm_wday<5:
                    print(f"{time_to_str(time.time())},重启服务")
                    break
            time.sleep(60)  # 每5分钟检测一次

def 打开微信读书(阅读时间,测试标识=0):
    for proc in psutil.process_iter():
        try:
            if proc.name() == "wereader.exe":
                os.system(r'taskkill /F /IM {}'.format("wereader.exe"))
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            pass
    if 测试标识==0:
        weixinPath=r"C:\Users\Administrator\AppData\Local\Programs\wereader"    #云服务器地址
    else:
        weixinPath = r"C:\Users\AXZQ\AppData\Local\Programs\wereader"
    os.startfile(os.path.join(weixinPath,"wereader.exe"))
    time.sleep(10)

    # 获取exe文件窗口句柄
    hwnd = win32gui.FindWindow(None, "微读")
    # 置顶窗口
    win32gui.SetWindowPos(hwnd, win32con.HWND_TOPMOST, 0, 0, 0, 0,win32con.SWP_NOMOVE | win32con.SWP_NOSIZE)

    # pyautogui.press("tab")
    # pyautogui.press("enter")
    getButton(os.path.join(pyPath,"autoReader1.jpg"))
    # print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")+"执行任务：打开微信读书")
    send_wechat_msg(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + "执行任务：打开微信读书")
    time.sleep(阅读时间)    # 休眠1个小时，杀掉进程
    for proc in psutil.process_iter():
        try:
            if proc.name() == "wereader.exe":
                os.system(r'taskkill /F /IM {}'.format("wereader.exe"))
                send_wechat_msg(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + "执行任务：关闭微信读书")
        except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
            pass

while True:

    if time.localtime()[3] >=开始阅读时间  :
        print(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") +"运行一次")
        # and time.localtime()[4] >= 5
        打开微信读书(每天阅读时间,测试标识=1)
        time.sleep(程序休眠时间)  # 休眠一天
schedule.every().day.at("20:00").do(统计账单数据)
# schedule.every(1).minutes.do(统计账单数据)
while True:
    schedule.run_pending()
    time.sleep(86400)


